"""
HTTP服务器示例。
1.0功能列表：
主要功能：获取A点到B点路线。
缓存管理功能：
1 查询缓存范围，当前地图缓存的版本号，当前天气缓存的版本号。
2 设置缓存范围，并重新生成缓存文件，重新加载缓存。
3 定时查询是否有新的地图数据和天气数据，如有则生成新的缓存文件并重新加载它到内存。
"""
import json
import urllib
from http.server import HTTPServer, BaseHTTPRequestHandler
from navieng.local_cache import LocalCache

class NErrorCode:
    ok = {"code": 0, "description": "ok"}
    unknown_error = {"code": 1, "status": "unknown error"}
    user_already_exist = '{"code":2,"description":"user already exist"}'
    missing_parameter = '{"code": 3, "description": "miss parameter"}'
    user_not_exist = '{"code": 4, "description": "user not exists"}'
    bad_parameter = '{"code": 5, "description": "bad parameter"}'
    out_of_sync = '{"code": 6, "description": "fatal error!out of sync!"}'
    no_such_trans_id = '{"code": 7, "description": "not such trans id"}'
    res_file_note_exist = '{"code": 8, "description": "resource file not exist"}'
    no_such_file = '{"code": 9, "description": "no such file"}'

class Request(BaseHTTPRequestHandler):
    timeout = 5
    server_version = "Apache"  # 设置服务器返回的的响应头

    def __do_respond(self, respond_str: str):
        # The response header.
        self.send_response(200)
        self.send_header("Content-type", "application/json")  # 设置post时服务器的响应头
        # self.send_header("test","This is post!")
        self.end_headers()
        print("[==>]", respond_str)
        self.wfile.write(respond_str.encode("utf-8"))  # 提交post数据时，服务器跳转并展示的页面内容

    def do_GET(self):
        print(self.headers)
        print(self.path)
        path: str = self.path

        if path == "/":
            self.send_response(200)
            self.send_header("Content-type", "text/html")  # 设置服务器响应头
            self.end_headers()
            buf = 'Welcome to python test server for navieng.'
            # 里面需要传入二进制数据，用encode()函数转换为二进制数据   #设置响应body，即前端页面要展示的数据
            self.wfile.write(buf.encode())
            return
        if path == "/version":
            self.__do_respond('{"code":0, "description": "OK", "version":"1.0"}')
            return
        return self.__do_respond(NErrorCode.bad_parameter)

    def __query_cache_area(self):
        pass
    # we do not need `post` yet
    # def __do_query_version(self, post_field: str) -> None:
    #     query_data = json.loads(post_field)
    #     print(query_data)
    #     respond = {"code": 0, "description": "OK", "version": "1.0"}
    #     self.__do_respond(json.dumps(respond))
    #
    # def do_POST(self):
    #     path = self.path
    #     print("path is:", path)
    #     # 获取post提交的数据
    #     datas = self.rfile.read(int(self.headers['content-length']))  # 固定格式，获取表单提交的数据type(data) = <class bytes>
    #     datas = urllib.parse.unquote(datas.decode("utf-8", 'ignore'))  # type(data) = <class str>
    #     print("data is:", datas)
    #     if path == "/query_version/":
    #         return self.__do_query_version(datas)
    #
    #     self.send_response(200)
    #     self.send_header("Content-type", "application/json")  # 设置post时服务器的响应头
    #     # self.send_header("test","This is post!")
    #     self.end_headers()
    #
    #     data = {'code': 1, 'description': 'unknow'}
    #     json_data = json.dumps(data)
    #     print("respond body:", json_data)
    #     self.wfile.write(json_data.encode())  # 提交post数据时，服务器跳转并展示的页面内容


if __name__ == '__main__':
    server = HTTPServer(("127.0.0.1",8082), Request)
    print("Starting server, listen at: 127.0.0.1:8082")
    server.serve_forever()
